package com.start.common;

import cn.hutool.core.util.ReUtil;
import com.start.common.dic.DicApi;
import com.start.common.dic.DicApiManage;
import com.start.common.tools.SpringContextTools;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

@Configuration
@ComponentScan({"com.start.common.**"})
@MapperScan({"com.start.common.mappers.**"})
public class StartCommonAutoConfiguration implements InitializingBean {
    private static final Pattern PATTERN = Pattern.compile("//+");
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        DicApiManage dicApiManage = DicApiManage.getInstance();
        Object bean = applicationContext.getBean("requestMappingHandlerMapping");
        RequestMappingHandlerMapping mapping = (RequestMappingHandlerMapping) bean;
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
            HandlerMethod handlerMethod = entry.getValue();
            DicApi dicApi = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), DicApi.class);
            if (dicApi == null) continue;
            RequestMappingInfo mappingInfo = entry.getKey();
            Set<String> patterns = mappingInfo.getPatternsCondition().getPatterns();
            for (String url : patterns) {
                dicApiManage.addApi(dicApi, ReUtil.replaceAll(SpringContextTools.getContextPath() + url, PATTERN, "/"));
            }
        }
    }
}
